import { defineComponent, PropType, Ref, ref, watch } from 'vue';
import { useNamespace } from '@ibiz-template/vue3-util';
import { IDEFormItem, IEditor } from '@ibiz/model-core';
import { FormItemController } from '@ibiz-template/runtime';
import { RuntimeError } from '@ibiz-template/core';
import './form-item-g6-design.scss';

export const FormItemG6Design = defineComponent({
  name: 'FormItemG6Design',
  props: {
    modelData: {
      type: Object as PropType<IDEFormItem>,
      required: true,
    },
    controller: {
      type: FormItemController,
      required: true,
    },
  },
  setup(props) {
    const ns = useNamespace('form-item');
    const c = props.controller;
    const data: Ref<IData | null> = ref(null);
    let config: IData | null = null;
    const initConfig = () => {
      const editor: IEditor | undefined = c.model.editor;
      if (editor && editor.editorParams) {
        try {
          Object.keys(editor.editorParams).forEach(key => {
            if (key === 'config') {
              config = JSON.parse(editor.editorParams![key]);
            }
          });
        } catch (error) {
          throw new RuntimeError('JSON 解析错误');
        }
      }
    };
    initConfig();

    const handleData = (value: string) => {
      let item: IData | null = null;
      try {
        item = JSON.parse(value);
        if (item) {
          data.value = {
            edges: item.psdelogiclinks,
            nodes: item.psdelogicnodes,
          };
        }
      } catch (error) {
        throw new RuntimeError('JSON 解析错误');
      }
    };

    watch(
      () => c.value,
      newValue => {
        handleData(newValue as string);
      },
    );

    const handleSelectChange = (arg: IParams) => {};

    return { ns, c, data, handleSelectChange, config };
  },
  render() {
    if (!this.c.state.visible) {
      return null;
    }
    return (
      <iBizRelationshipDesign
        data={this.data}
        config={this.config}
        onSelectChange={(arg: IParams) => this.handleSelectChange(arg)}
      ></iBizRelationshipDesign>
    );
  },
});
export default FormItemG6Design;
